package com.xiaomi.shoppinglist

import android.content.Intent
import android.os.Bundle
import android.widget.RemoteViewsService
import android.util.Log

class RepeatableListService : RemoteViewsService() {
    private val TAG = "RepeatableListService"

    override fun onGetViewFactory(intent: Intent): RemoteViewsFactory {
        Log.d(TAG, "onGetViewFactory called")
        val bundle = intent.extras
        val appWidgetId = bundle?.getInt(
            RemoteViewsService.EXTRA_APPWIDGET_ID,
            RemoteViewsService.INVALID_APPWIDGET_ID
        ) ?: RemoteViewsService.INVALID_APPWIDGET_ID

        return RepeatableListFactory(applicationContext, appWidgetId)
    }

    private class RepeatableListFactory(
        private val context: android.content.Context,
        private val appWidgetId: Int
    ) : RemoteViewsService.RemoteViewsFactory {
        private val TAG = "RepeatableListFactory"
        private var items: List<ShoppingItem> = emptyList()

        override fun onCreate() {
            Log.d(TAG, "onCreate called")
            // 初始化数据
            ShoppingListDatabase.init(context)
        }

        override fun onDataSetChanged() {
            Log.d(TAG, "onDataSetChanged called")
            // 当数据发生变化时更新列表
            val db = ShoppingListDatabase.getInstance(context)
            val scope = kotlinx.coroutines.GlobalScope
            scope.launch(kotlinx.coroutines.Dispatchers.IO) {
                items = db.shoppingItemDao().getActiveRepeatableItems()
            }
            // 等待数据加载完成
            Thread.sleep(100)
        }

        override fun onDestroy() {
            Log.d(TAG, "onDestroy called")
            // 清理资源
            items = emptyList()
        }

        override fun getCount(): Int {
            return items.size
        }

        override fun getViewAt(position: Int): RemoteViews {
            val item = items[position]
            val views = RemoteViews(context.packageName, R.layout.shopping_item)

            // 设置项名称
            views.setTextViewText(R.id.item_name, item.name)

            // 设置周期信息
            val unitArray = context.resources.getStringArray(R.array.interval_units)
            val intervalText = "每${item.reminderInterval}${unitArray[item.reminderUnit]}"
            views.setTextViewText(R.id.item_note, intervalText)
            views.setViewVisibility(R.id.item_note, RemoteViews.VISIBLE)

            // 设置复选框状态
            views.setChecked(R.id.item_checkbox, item.isCompleted)

            // 设置点击事件
            val fillInIntent = Intent()
            fillInIntent.putExtra(ShoppingListWidget.EXTRA_ITEM_ID, item.id)
            fillInIntent.putExtra(ShoppingListWidget.EXTRA_ITEM_TYPE, 1) // 1表示可重复
            views.setOnClickFillInIntent(R.id.item_checkbox, fillInIntent)
            views.setOnClickFillInIntent(R.id.item_name, fillInIntent)

            return views
        }

        override fun getLoadingView(): RemoteViews? {
            return null
        }

        override fun getViewTypeCount(): Int {
            return 1
        }

        override fun getItemId(position: Int): Long {
            return items[position].id
        }

        override fun hasStableIds(): Boolean {
            return true
        }
    }
}